<template>
  <div>
    <div v-show="activeStatu">
      <el-card class="box">
        <!-- 搜索筛选名称或标题 -->
        <div class="search-container">
          <div class="flex">
            <div class="package-name-label">套餐名称</div>
            <div class="time-top">套餐状态</div>
          </div>
          <div class="flex-box">
            <div> 
              <el-input v-model.trim="inputed" @input="filters" placeholder="输入内容" class="search-input">
                <template #prefix>
                  <el-icon class="el-input__icon">
                    <search />
                  </el-icon>
                </template>
              </el-input>
            </div>
            <div class="select-container">
              <el-select v-model="value" @change="ange_indexof" clearable placeholder="请选择" class="status-select">
                <el-option v-for="item in options" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </div>
          <div class="button-container">
            <div><el-button type="primary" @click="add" class="add-button">新增</el-button></div>
            <el-button type="danger" class="delete-button" @click="deleList">批量删除</el-button>
          </div>
          <!-- table表格数据展示 -->
          <div> 
            <el-table 
              :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
              class="data-table" 
              :cell-style="{ 'text-align': 'center' }" 
              lazy="true"
              v-el-table-infinite-scroll="handleTableScroll"
              :header-cell-style="{ 'text-align': 'center' }" 
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" fixed="left" />
              <el-table-column prop="id" label="序号" fixed="left" />
              <el-table-column prop="title" width="120" label="套餐名称" show-overflow-tooltip />
              <el-table-column prop="imgs" label="图片" width="130">
                <template #default="scope">
                  <div class="image-container">
                    <el-image 
                      class="table-image" 
                      :src="testName + scope.row.img"
                      :zoom-rate="1.2" 
                      :max-scale="7" 
                      :min-scale="0.2"
                      :preview-src-list="[testName + scope.row.img]" 
                      :initial-index="4"
                      fit="cover" 
                      preview-teleported />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="price" sortable width="130" label="套餐优惠价" show-overflow-tooltip />
              <el-table-column prop="old_price" width="130" label="套餐原价" />
              <el-table-column prop="quantity" width="100" sortable label="销量" />
              <el-table-column prop="" width="100" label="套餐状态">
                <template #default="scope">
                  <div class="handle">
                    <el-switch 
                      @change="funstatus(scope.row)"
                      :model-value="scope.row.status == 1 ? true : scope.row.status == 0 ? false : scope.row.status"
                      inline-prompt />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="createtime" width="180" show-overflow-tooltip label="创建时间" />
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <div class="handle">
                    <div @click="edit(scope.row)" class="edit-button">编辑</div>
                    <div class="action-spacing"></div>
                    <div @click="deletes(scope.row)" class="delete-button">删除</div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="paging">
            <el-pagination 
              v-model:current-page="currentPage" 
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]" 
              :small="small" 
              :disabled="disabled" 
              background
              layout="total, sizes, prev, pager, next, jumper" 
              :total="activeList.length" />
          </div>
          <!-- 删除弹窗 -->
          <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
            <div class="delete-message">确认删除该套餐吗?</div>
            <div class="dialog-footer">
              <el-button @click="centerDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="deleteid">确 定</el-button>
            </div>
          </el-dialog>
        </div>
        <el-dialog v-model="shows" title="是否要删除" center width="20vw">
          <el-button @click="shows = false">取 消</el-button>
          <el-button type="primary" @click="oks">确 定</el-button>
        </el-dialog>
        <!-- 批量删除 -->
        <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
          <div class="batch-delete-message">确认删除这批数据吗?</div>
          <span slot="footer" class="dialog-footer">
            <div></div>
            <div>
              <el-button @click="centerDialogVisiblet = false">取 消</el-button>
              <el-button type="primary" @click="deleteid_t">确 定</el-button>
            </div>
          </span>
        </el-dialog>
      </el-card>
    </div>
    <!-- 第二块 -->
    <div v-show="activeStatud" class="form-container">
      <el-card class="form-card">
        <div class="form-title">{{ title }}</div>
        <div class="divider"></div>
        <div class="form-content">
          <el-form 
            ref="ruleFormRef" 
            class="rule-form" 
            :model="ruleForm" 
            status-icon 
            :rules="rules"
            label-position="left" 
            label-width="auto">
            <div class="form-row">
              <div class="form-col">
                <el-form-item label="选择门店" prop="name" class="form-item">
                  <el-select 
                    :disabled="disableds" 
                    v-model="ruleForm.name" 
                    placeholder="请选择"
                    class="form-select">
                    <el-option v-for="item in optionss" :key="item.id" :label="item.title" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="套餐名称" prop="jqfl" class="form-item">
                  <el-input v-model.trim="ruleForm.jqfl" placeholder="请输入" class="form-input" />
                </el-form-item>
                <el-form-item label="适应人群" prop="jqry" class="form-item">
                  <el-input v-model.trim="ruleForm.jqry" placeholder="请输入" class="form-input" />
                </el-form-item>
                <el-form-item label="有效期" prop="jqdh" class="form-item">
                  <el-input v-model.trim="ruleForm.jqdh" placeholder="请输入" class="form-input" />
                </el-form-item>
                <!-- 单图封面图片 -->
                <el-form-item prop="covers" label="套餐海报" class="form-item">
                  <el-upload 
                    list-type="picture-card" 
                    accept=".jpeg,.png,.jpg,.bmp,.gif"
                    :on-preview="handlePictureCardPreviewt" 
                    :on-remove="handleRemovet"
                    :file-list="fileListt" 
                    :before-upload="beforeAvatarUploadt"
                    class="upload-container">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item prop="switch" label="上下架" class="form-item">
                  <el-switch @change="funstate()" v-model="ruleForm.switch" />
                </el-form-item>
              </div>
              <div class="form-col">
                <el-form-item label="套餐原价" prop="jqdz" class="form-item">
                  <div class="custom-number-input">
                    <button type="button" @click="decreaseOriginalPrice">-</button>
                    <input 
                      type="text" 
                      v-model="ruleForm.jqdz" 
                      @input="handleOriginalPriceInput" 
                      @blur="validateOriginalPriceInput" 
                    />
                    <button type="button" @click="increaseOriginalPrice">+</button>
                  </div>
                </el-form-item>
                <el-form-item label="套餐现价" prop="jd" class="form-item">
                  <div class="custom-number-input">
                    <button type="button" @click="decreaseCurrentPrice">-</button>
                    <input 
                      type="text" 
                      v-model="ruleForm.jd" 
                      @input="handleCurrentPriceInput" 
                      @blur="validateCurrentPriceInput" 
                    />
                    <button type="button" @click="increaseCurrentPrice">+</button>
                  </div>
                </el-form-item>
                <!-- 多图片上传   -->
                <el-form-item prop="img" label="套餐轮播" class="form-item">
                  <el-upload 
                    list-type="picture-card" 
                    accept=".jpeg,.png,.jpg,.bmp,.gif"
                    :on-exceed="exceed_li" 
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove" 
                    :file-list="fileList" 
                    :on-change="handleChange"
                    :on-success="handleSuccess" 
                    :before-upload="beforeUpload" 
                    :auto-upload="false"
                    :limit="4"
                    class="upload-container">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </div>
            </div>
            <div class="form-spacer"></div>
            <el-form-item label="套餐介绍" prop="introduce" class="form-item">
              <vue-ueditor-wrap v-model.trim="ruleForm.introduce" :config="editorConfig" editor-id="editor-demo-01"></vue-ueditor-wrap>
            </el-form-item>
            <div class="form-spacer"></div>
          </el-form>
          <div class="form-footer">
            <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
            <el-button @click="closes(ruleFormRef)">取消</el-button>
          </div>
        </div>
      </el-card>
    </div>
    <el-dialog v-model="dialogVisible">
      <img class="preview-image" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <el-dialog v-model="dialogVisiblet">
      <img class="preview-image" :src="dialogImageUrlt" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { activeAdd, activeDel, scienList, ticketStatus, asst_add } from '../../../api/active/index';
import { ElMessage, ElCard, ElDropdown } from 'element-plus';
import { Plus, Search, ArrowLeft, ArrowDown, RefreshRight } from '@element-plus/icons-vue';
import { scenicUpload } from '../../../api/uploading/index';
import { lark_list_shop_save, lark_list_goods_status, lark_list_shop, lark_list_goods_save_add, lark_list_goods_save_del } from '../../../api/arklist/index'
import { useRoute, useRouter } from 'vue-router';
const dialogVisible = ref(false);
// 富文本引入
// 富文本
const editorConfig = reactive({
	// 编辑器不自动被内容撑高
	autoHeightEnabled: false,
	// 初始容器高度
	initialFrameHeight: 200,
	// 初始容器宽度
	initialFrameWidth: '100vw',
	UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
	serverUrl: '/pc/common/ueditor', // 服务端接⼝
	uploadUrl: '/UEditor',
	// enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，// 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
});
// 创建数据变量
const activeList = ref([]);
const activeStatu = ref(true)
const activeStatud = ref(false)
import { inject } from 'vue'
import { status } from 'nprogress';
import { log } from 'console';
// 全局域名
const testFn = inject('testFn')
testFn()
const testName = inject('testName')
const dialogTableVisible = ref(false);
const statused = ref('1');
// 表格页码数
const inputed = ref('');
const pageSize = ref(5);
const currentPage = ref(1);
const copyList = ref([]);
const files = ref(false);
// 请求接口并开局渲染
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);
// 编辑评分值
const value_f = ref()
// 搜索框下拉
const value = ref('')
const options = [
	{
		value: '1',
		label: '开启'
	}, {
		value: '0',
		label: '关闭'
	}]
const optionss = ref([])
// 请求数据渲染
render();
function render() {
	lark_list_shop_save({
		token: tokens.token,
		uid: tokens.userinfo.id
	}, {
		userid: tokens.userinfo.id,
		uid: tokens.userinfo.id
	}).then((res) => {
		console.log(res);
		activeList.value = res.data;
		copyList.value = res.data;
	});
	lark_list_shop({
		token: tokens.token,
		uid: tokens.userinfo.id
	}, {
		uid: tokens.userinfo.id
	}).then((res) => {
		console.log(res);
		optionss.value = res.data
	});
}

// 上传图片返回路径
const fileImg = ref([])
const Delete = ref('')
const fileList = ref([])
const fileListQW = ref([])
// 照片移除后的数据
const fileremover = ref([])
const iitimg = ref([])
// 图片移除
// 图片移除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
	console.log(uploadFile)
	// console.log(uploadFiles)
	const formData = new FormData();
	formData.append('file', uploadFile.raw);
	scenicUpload(formData).then(res => {
		console.log(res.data.url);
		for (let i = 0; i < iitimg.value.length; i++) {
			if (iitimg.value[i] == res.data.url) {
				iitimg.value.splice(i, 1)
				break;
			}
		}
	})

	if (uploadFiles.length < 1) {
		ruleForm.img = ''
	}

	for (let i = 0; i < iitimg.value.length; i++) {
		if (iitimg.value[i] == uploadFile.url.slice(testName.length, 106)) {
			iitimg.value.splice(i, 1)
			// console.log(i);

		}
	}


	console.log(iitimg.value);
}
const dialogImageUrl = ref('')
const dialogVisiblet = ref(false)
const dialogImageUrlt = ref('')
// 图片放大视图
const handlePictureCardPreview = (file) => {
	// console.log(file.raw.name);
	dialogImageUrl.value = file.url;
	dialogVisible.value = true;
}
const imgList = ref([])
// 图片超出限制
const exceed_li = () => {
	ElMessage({
		message: '最多可上传四张',
		type: 'warning',
	})
}
// 图片上传回调函数
const handleChange = (file, fileLists) => {
	const fileName = file.name
	const fileType = fileName.substring(fileName.lastIndexOf('.'))
	const formData = new FormData();
	formData.append('file', file.raw);
	scenicUpload(formData).then(res => {
		console.log(res.code);
		if (res.code == 1) {
			ruleForm.img = res.data.url
			console.log(res.data, '上传成功');
			fileImg.value.push(res.data.url)
			fileremover.value.push(res.data.url)
			imgList.value.push(res.data.url.split(','))
			iitimg.value.push(res.data.url)
		} else if (res.code == 0) {
			ElMessage.error('图片不能大于2MB!')
			for (let i = 0; i < fileLists.length; i++) {
				if (i === fileLists.length - 1) {
					fileLists.splice(i, 1)
				}
			}
		}
	})
	// }
	// jpeg,.png,.jpg,.bmp,.gif
	if (
		fileType === '.jpg' ||
		fileType === '.png' ||
		fileType === '.jpeg' ||
		fileType === '.bmp' ||
		fileType === '.gif'
	) {
	} else {
		ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
		return false
	}
	console.log(file);
	console.log(file.raw);




};
// success成功回调函数 图片
const handleSuccess = (response, file, fileList) => {

	console.log('File uploaded successfully:', response, file, fileList);
	console.log(fileImg.value);

};
const beforeUpload = (rawFile) => {
	console.log(rawFile);
	console.log(1);
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('Avatar picture must be JPG format!')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('Avatar picture size can not exceed 2MB!')

		return false
	}
	return true
}
// 查看图片放大
const fileListt = ref([]);
const handlePictureCardPreviewt = (file) => {
	// console.log(file.raw.name);
	dialogImageUrlt.value = file.url;
	dialogVisiblet.value = true;
}
// 图片移除
const handleRemovet = (file, fileListt) => {
	console.log(file, fileListt);
	if (fileListt.length < 1) {
		ruleForm.covers = ''
	}
};
// 图片上传回调事件
const beforeAvatarUploadt = (file) => {
	const fileName = file.name
	const fileType = fileName.substring(fileName.lastIndexOf('.'))
	// jpeg,.png,.jpg,.bmp,.gif
	if (
		fileType === '.jpg' ||
		fileType === '.png' ||
		fileType === '.jpeg' ||
		fileType === '.bmp' ||
		fileType === '.gif'
	) {
	} else {
		ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
		return false
	}
	console.log(file);
	// 压缩图片
	compressImage(file).then(compressedBlob => {
		const formData = new FormData();
		formData.append('file', compressedBlob, file.name);
		if (file.size / 1024 / 1024 > 2) {
			console.log(file.size / 1024 / 1024);
			ElMessage.error('图片不能大于2MB!')
			return false
		} else {

			console.log(formData);
			scenicUpload(formData).then(res => {
				console.log(res);

				// fileImg.cover = res.data.url
				fileListt.value = [{
					name: 'plant-1.png',
					url: testName + res.data.url,
				}]
				ruleForm.covers = res.data.url
			})
		}
	});
	return false; // 阻止默认上传行为

}
const compressImage = (file) => {
	const reader = new FileReader();
	reader.readAsDataURL(file);
	return new Promise((resolve) => {
		reader.onload = e => {
			const img = new Image();
			img.src = e.target.result;
			img.onload = () => {
				const canvas = document.createElement('canvas');
				const ctx = canvas.getContext('2d');
				const { width, height } = img;
				canvas.width = width;
				canvas.height = height;
				ctx.drawImage(img, 0, 0, width, height);
				// 可以在这里调整压缩质量和尺寸
				const quality = 0.7; // 压缩质量
				const newImageData = canvas.toDataURL('image/jpeg', quality);
				const resizedBlob = dataURLtoBlob(newImageData);
				console.log(ctx);
				resolve(resizedBlob);
			};
		};
	});
};
const dataURLtoBlob = (dataurl) => {
	const arr = dataurl.split(',');
	const mime = arr[0].match(/:(.*?);/)[1];
	const bstr = atob(arr[1]);
	let n = bstr.length;
	const u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], { type: mime });
};
// 上下架
let statust = ref('');
function funstatus(e) {
	console.log(e);

	if (e.status == '1') {
		statust.value = '0';
	} else if (e.status == '0') {
		statust.value = '1';
	}
	console.log(statust.value);
	console.log(e);


	lark_list_goods_status(
		{
			token: tokens.token,
			uid: tokens.userinfo.id,
		},
		{
			// userid: tokens.userinfo.id,
			uid: tokens.userinfo.id,
			ids: e.id,
			status: statust.value
		}
	).then((res) => {
		console.log(res);
		if (res.code == 1) {
			ElMessage({
				message: '操作成功',
				type: 'success',
			});
			render();
		} else if (res.code == 0) {
			ElMessage({
				message: res.msg,
				type: 'warning',
			});
		}
	});
}

// 表单对象
const ruleForm = reactive({
	name: '',
	img: '',
	jqfl: '',
	jqry: '',
	jqdh: '',
	yysj: '',
	jqdz: '',
	jd: '',
	wd: '',
	dpdz: '',
	covers: '',
	introduce: '',
	switch: '1'
});
// 套餐原价减少
const decreaseOriginalPrice = () => {
  if (ruleForm.jqdz && parseFloat(ruleForm.jqdz) > 0.01) {
    ruleForm.jqdz = (parseFloat(ruleForm.jqdz) - 0.01).toFixed(2);
  }
};

// 套餐原价增加
const increaseOriginalPrice = () => {
  if (ruleForm.jqdz) {
    ruleForm.jqdz = (parseFloat(ruleForm.jqdz) + 0.01).toFixed(2);
  } else {
    ruleForm.jqdz = '0.01';
  }
};

// 套餐现价减少
const decreaseCurrentPrice = () => {
  if (ruleForm.jd && parseFloat(ruleForm.jd) > 0.01) {
    ruleForm.jd = (parseFloat(ruleForm.jd) - 0.01).toFixed(2);
  }
};

// 套餐现价增加
const increaseCurrentPrice = () => {
  if (ruleForm.jd) {
    ruleForm.jd = (parseFloat(ruleForm.jd) + 0.01).toFixed(2);
  } else {
    ruleForm.jd = '0.01';
  }
};

// 处理套餐原价输入
const handleOriginalPriceInput = (event) => {
  let value = event.target.value;
  value = value.replace(/[^0-9.]/g, '');
  
  // 确保只有一个小数点
  const decimalIndex = value.indexOf('.');
  if (decimalIndex !== -1) {
    value = value.substring(0, decimalIndex + 3); // 保留两位小数
  }
  
  // 不允许前导零（除非是0.xx）
  if (value.startsWith('0') && value.length > 1 && value[1] !== '.') {
    value = value.substring(1);
  }
  
  ruleForm.jqdz = value;
};

// 处理套餐现价输入
const handleCurrentPriceInput = (event) => {
  let value = event.target.value;
  value = value.replace(/[^0-9.]/g, '');
  
  // 确保只有一个小数点
  const decimalIndex = value.indexOf('.');
  if (decimalIndex !== -1) {
    value = value.substring(0, decimalIndex + 3); // 保留两位小数
  }
  
  // 不允许前导零（除非是0.xx）
  if (value.startsWith('0') && value.length > 1 && value[1] !== '.') {
    value = value.substring(1);
  }
  
  ruleForm.jd = value;
};

// 验证套餐原价
const validateOriginalPriceInput = () => {
  const value = ruleForm.jqdz;
  const reg = /^\d+(\.\d{1,2})?$/;
  
  if (value && !reg.test(value)) {
    ElMessage({
      type: 'warning',
      message: '请输入有效的价格（最多两位小数）'
    });
    ruleForm.jqdz = '';
  } else if (value && parseFloat(value) <= 0) {
    ElMessage({
      type: 'warning',
      message: '价格必须大于0'
    });
    ruleForm.jqdz = '';
  }
};

// 验证套餐现价
const validateCurrentPriceInput = () => {
  const value = ruleForm.jd;
  const reg = /^\d+(\.\d{1,2})?$/;
  
  if (value && !reg.test(value)) {
    ElMessage({
      type: 'warning',
      message: '请输入有效的价格（最多两位小数）'
    });
    ruleForm.jd = '';
  } else if (value && parseFloat(value) <= 0) {
    ElMessage({
      type: 'warning',
      message: '价格必须大于0'
    });
    ruleForm.jd = '';
  }
};
const ruleFormRef = ref('');
const rules = reactive({
	name: [
		{
			required: true,
			message: '请选择门店',
			trigger: 'blur',
		},
	],
	jqfl: [
		{
			required: true,
			message: '请输入套餐名称',
			trigger: 'blur',
		},
	],
	jqry: [
		{
			required: true,
			message: '请输入适应人群',
			trigger: 'blur',
		}
	],
	jqdh: [
		{
			required: true,
			message: '请输入有效期',
			trigger: 'blur',
		},
	],
	img: [
		{
			required: true,
			message: '请上传轮播图片',
			trigger: 'change',
		},
	],
	yysj: [
		{
			required: true,
			message: '请输入营业时间',
			trigger: 'change',
		},
	],
	dpdz: [
		{
			required: true,
			message: '请输入套餐原价',
			trigger: 'change',
		},
	],
  jqdz: [
    { 
      required: true, 
      message: '请输入套餐原价', 
      trigger: 'blur' 
    },
    { 
      validator: (rule, value, callback) => {
        const reg = /^\d+(\.\d{1,2})?$/;
        if (!value) {
          callback(new Error('请输入套餐原价'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入有效的价格（最多两位小数）'));
        } else if (parseFloat(value) <= 0) {
          callback(new Error('价格必须大于0'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  jd: [
    { 
      required: true, 
      message: '请输入套餐现价', 
      trigger: 'blur' 
    },
    { 
      validator: (rule, value, callback) => {
        const reg = /^\d+(\.\d{1,2})?$/;
        if (!value) {
          callback(new Error('请输入套餐现价'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入有效的价格（最多两位小数）'));
        } else if (parseFloat(value) <= 0) {
          callback(new Error('价格必须大于0'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
	wd: [
		{
			required: true,
			message: '请输入维度',
			trigger: 'change',
		},
	],
	covers: [
		{
			required: true,
			message: '请上传图片',
			trigger: 'change',
		},
	],
	introduce: [
		{
			required: true,
			message: '请输入简介',
			trigger: 'change',
		},
	],

});

function validateEmailDomain(rule, value, callback) {
	if (value === '') {
		callback(new Error('结束时间不能为空'));
	} else if (value < ruleForm.start_time) {
		// 假设我们只允许 @example.com 的邮箱  
		callback(new Error('结束时间不能小于开始时间'));
	} else {
		callback();
	}
}
const ids = ref('');
const stattess = ref('0')
// 点击switch开关
const funstate = () => {
	console.log(ruleForm.switch);
	if (ruleForm.switch == true) {
		stattess.value = '1'
	} else if (ruleForm.switch == false) {
		stattess.value = '0'
	}
}
// 点击确认或编辑
const submitForm = (formEl) => {
	console.log(iitimg.value);
	console.log(stattess.value);

	if (!formEl) return;
	formEl.validate((valid) => {
		if (valid) {
			if (statused.value == '1') {
				lark_list_goods_save_add({ token: tokens.token, uid: tokens.userinfo.id }, {

					uid: tokens.userinfo.id,
					title: ruleForm.jqfl,
					sort: 1,
					num: ruleForm.jqry,
					img: ruleForm.covers,
					imgs: iitimg.value.join(','),
					inner_date: ruleForm.jqdh,
					quantity: 1,
					old_price: ruleForm.jqdz,
					price: ruleForm.jd,
					shop_id: ruleForm.name,
					status: stattess.value,
					state: 1,
					content: ruleForm.introduce
				}).then((res) => {
					if (res.code == 1) {
						console.log(res);

						ElMessage({
							message: '新增成功',
							type: 'success',
						});
						setTimeout(() => {
							activeStatud.value = false;
							activeStatu.value = true;
							fileList.value = []
						}, 1200);

						render();
					} else {

					}
				});
			} else
				if (statused.value == '2') {


					lark_list_goods_save_add({ token: tokens.token, uid: tokens.userinfo.id }, {

						uid: tokens.userinfo.id,
						id: ids.value,
						title: ruleForm.jqfl,
						sort: 1,
						num: ruleForm.jqry,
						img: ruleForm.covers,
						imgs: iitimg.value.join(','),
						inner_date: ruleForm.jqdh,
						quantity: 1,
						old_price: ruleForm.jqdz,
						price: ruleForm.jd,
						shop_id: ruleForm.name,
						status: stattess.value,
						state: 1,
						content: ruleForm.introduce
					}).then((res) => {
						if (res.code == '1') {

							ElMessage({
								message: '编辑成功',
								type: 'success',
							});
							setTimeout(() => {
								activeStatud.value = false;
								activeStatu.value = true;
								fileList.value = []
								fileListt.value = []
								ruleForm.covers = ''
								ruleForm.dpdz = ''
								ruleForm.img = ''
								ruleForm.introduce = ''
								ruleForm.jd = ''
								ruleForm.jqdh = ''
								ruleForm.jqdz = ''
								ruleForm.jqfl = ''
								ruleForm.jqry = ''
								ruleForm.name = ''
								ruleForm.yysj = ''
								ruleForm.wd = ''
								ruleForm.switch = false
							}, 1200);

							render();
						} else {
							ElMessage({
								message: '编辑失败，不能和原数据一致',
								type: 'warning',
							});
						}
					});
				}
		}
		else {
			ElMessage({
				message: '编辑失败',
				type: 'error',
			});

		}
	});
};

const disableds = ref(false);
// 关闭新增
const closes = (formEl) => {
	console.log(formEl);
	activeStatu.value = true
	activeStatud.value = false
	formEl.resetFields();
	formEl.clearValidate()
	dialogTableVisible.value = false;
	files.value = false;
	ruleForm.name = ''
	fileList.value = []
	fileListt.value = []

};
const title = ref('')
// 点击新增
const add = () => {
	statused.value = '1';
	activeStatud.value = true
	activeStatu.value = false
	title.value = '新增'
	disableds.value = false
}

// 点击编辑
function edit(item) {
	console.log(item);
	title.value = '编辑'
	statused.value = '2';
	stattess.value = item.status
	if (item.status == 1) {
		ruleForm.switch = true
	} else {
		ruleForm.switch = false
	}
	// Object.assign(ruleForm, item);
	ids.value = item.id;
	activeStatud.value = true
	activeStatu.value = false
	ruleForm.name = item.shop_id
	ruleForm.jqfl = item.title
	ruleForm.jqry = item.num
	ruleForm.jqdh = item.inner_date
	ruleForm.jqdz = item.old_price
	ruleForm.jd = item.price
	iitimg.value = item.imgs.split(',')

	Delete.value = item.banner
	ruleForm.introduce = item.content
	ruleForm.covers = item.img
	ruleForm.img = item.imgs.split(',')
	// 封面图片回显
	fileListt.value = [{
		url: testName + item.img,
	}]
	for (let i = 0; i < item.imgs.split(',').length; i++) {
		fileListQW.value.push(testName + item.imgs.split(',')[i])
		fileList.value.push(
			{
				url: testName + item.imgs.split(',')[i],
			});
	}
	disableds.value = true;
}
// 点击上传出现弹窗
function deletes(item) {
	console.log(item);
	centerDialogVisible.value = true;
	deleteids.value = item.id;
}
const deleteids = ref('');
const centerDialogVisible = ref(false);
// 确认删除
function deleteid() {
	lark_list_goods_save_del(
		{
			token: tokens.token,
			uid: tokens.userinfo.id,
		},
		{
			userid: tokens.userinfo.id,
			uid: tokens.userinfo.id,
			ids: deleteids.value,
		}
	).then((res) => {
		if (res.code == '1') {
			centerDialogVisible.value = false;
			ElMessage({
				message: '删除成功',
				type: 'success',
			});
			render();
		}
	});
}
// 分类名称搜索
function filters() {
	currentPage.value = 1
	console.log(inputed.value);
	let a = [];
	activeList.value = copyList.value.filter(function (item) {
		// 判断是否满足搜索条件
		if (String(item.title).indexOf(String(inputed.value)) > -1) {
			return a;
		}
	});
	currentPage.value = 1

}
// 上下架搜索
const ange_indexof = (e) => {
	console.log(e);
	if (e == undefined) {
		render()
	}
	let a = [];
	activeList.value = copyList.value.filter(function (item) {
		// 判断是否满足搜索条件
		if (String(item.status).indexOf(String(e)) > -1) {
			return activeList;
		}
	});
	currentPage.value = 1

}
const shows = ref(false);
// 删除批量
// 全选单选
const SelectArr = ref([])
const All_Delete = ref([])
const handleSelectionChange = (val) => {
	All_Delete.value = []
	SelectArr.value = val
	SelectArr.value.forEach(item => {
		console.log(item);
		All_Delete.value.push(item.id)
	})
	console.log(All_Delete.value);
}
// 批量删除
// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
	st.value = []
	console.log(All_Delete.value);
	st.value.push(All_Delete.value)
	if (All_Delete.value == '') {
		ElMessage({
			message: '请勾选要删除的套餐',
			type: 'warning',
		})
	} else {
		centerDialogVisiblet.value = true
	}
}
// 确认批量删除
const deleteid_t = () => {
	lark_list_goods_save_del({
		token: tokens.token,
		uid: tokens.userinfo.id
	}, {
		userid: tokens.userinfo.id,
		uid: tokens.userinfo.id,
		ids: st.value.join(','),

	}).then(res => {
		console.log(res, '删除成功或失败回调');
		centerDialogVisiblet.value = false;
		render();
		ElMessage({
			message: '删除成功',
			type: 'success',
		})
	})
}
</script>

<style>
/* 你的样式 */
@import url("https://cache.amap.com/lbs/static/main1119.css");

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}

.box-card {
  display: flex;
  height: 300px;
  width: 90%;
}

.handle {
  display: flex;
  align-items: center;
  justify-content: center;
}

.paging {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  height: 70px;
}

.flex {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
}

.flex-box {
  display: flex;
  width: 100%;
  align-items: center;
}

.el-upload-list--picture-card {
  --el-upload-list-picture-card-size: 100px;
  display: inline-flex;
  flex-wrap: wrap;
  margin: 0;
}

.el-upload--picture-card {
  --el-upload-picture-card-size: 99px;
  align-items: center;
  background-color: var(--el-fill-color-lighter);
  border: 1px dashed var(--el-border-color-darker);
  border-radius: 6px;
  box-sizing: border-box;
  cursor: pointer;
  display: inline-flex;
  height: var(--el-upload-picture-card-size);
  justify-content: center;
  vertical-align: top;
  width: var(--el-upload-picture-card-size);
}

/* 新增样式类 */
.search-container {
  padding: 10px;
}

.package-name-label {
  width: 220px;
}

.time-top {
  margin-left: 20px;
}

.search-input {
  width: 220px;
}

.select-container {
  margin-left: 20px;
}

.status-select {
  width: 240px;
}

.button-container {
  display: flex;
  margin-top: 10px;
}

.add-button {
  margin-right: 10px;
}

.delete-button {
  color: white;
  cursor: pointer;
}

.data-table {
  margin-top: 10px;
  width: 100%;
}

.image-container {
  display: flex;
  justify-content: center;
}

.table-image {
  width: 40px;
  height: 40px;
}

.edit-button {
  color: rgba(64, 158, 255, 1);
  cursor: pointer;
}

.action-spacing {
  width: 15px;
}

.delete-message {
  font-size: 16px;
  padding-bottom: 20px;
}

.batch-delete-message {
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: end;
}

.form-container {
  padding: 10px;
}

.form-card {
  width: 96%;
  margin-left: 2%;
  margin-top: 1%;
  position: relative;
  height: auto;
}

.form-title {
  padding: 10px;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: rgba(195, 195, 195, 1);
}

.form-content {
  margin-top: 50px;
  margin-left: 100px;
}

.rule-form {
  width: 90%;
}

.form-row {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.form-col {
  width: 48%;
}

.form-item {
  width: 90%;
}

.form-select {
  width: 90%;
}

.form-input {
  width: 90%;
}

.upload-container {
  margin-top: 10px;
}

.form-spacer {
  height: 40px;
}

.form-footer {
  position: absolute;
  bottom: 10px;
  right: 40px;
}

.preview-image {
  width: 90%;
  height: 90%;
}

/* 步进器样式 */
.custom-number-input {
  display: flex;
  align-items: center;
  width: 150px;
}

.custom-number-input button {
  width: 30px;
  height: 30px;
  border: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  color: #606266;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  user-select: none;
}

.custom-number-input button:hover {
  background-color: #e4e7ed;
}

.custom-number-input button:first-child {
  border-radius: 4px 0 0 4px;
}

.custom-number-input button:last-child {
  border-radius: 0 4px 4px 0;
}

.custom-number-input input {
  flex: 1;
  height: 30px;
  border: 1px solid #dcdfe6;
  border-left: none;
  border-right: none;
  text-align: center;
  padding: 0 5px;
  font-size: 14px;
  outline: none;
  width: 60px;
}

.custom-number-input input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}
</style>